package BlockingQueue_12;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.BlockingQueue;

class Task implements Comparable<Task> {
    int priority;
    String name;

    public Task(int priority, String name) {
        this.priority = priority;
        this.name = name;
    }

    public int compareTo(Task other) {
        return Integer.compare(other.priority, this.priority); // 降序排列
    }
}

public class 优先级任务处理_PriorityBlockingQueue {
    public static void main(String[] args) throws InterruptedException
    {
        final int WORKER_COUNT = 3;
        final BlockingQueue<Task> queue = new PriorityBlockingQueue<>();

        // 创建工作线程
        for (int i = 0; i < WORKER_COUNT; i++) {
            final int workerId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        while (true) {
                            Task task = queue.take();
                            System.out.println("工作者 " + workerId + " 处理任务: " +
                                                       task.name + " (优先级:" + task.priority + ")");
                            Thread.sleep((long)(Math.random() * 500)); // 模拟处理时间
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "工作者-" + i).start();
        }

        // 提交任务
        for (int i = 0; i < 10; i++) {
            int priority = (int)(Math.random() * 10);
            String taskName = "任务-" + i;
            queue.put(new Task(priority, taskName));
            System.out.println("已提交: " + taskName + " (优先级:" + priority + ")");
        }
    }
}